package ro.ubbcluj.cs.damate.persistence.entities;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.List;

import static javax.persistence.CascadeType.*;
import static javax.persistence.FetchType.*;
import static ro.ubbcluj.cs.damate.utils.EntityUtils.*;

/**
 * @author Lóránd Fazakas (lorand)
 *         Date: 4/22/12
 *         Time: 1:13 AM
 */
@Table(name = "workspace", catalog = "damate")
@Entity
@PrimaryKeyJoinColumn(name = "parentEntity")
public class Workspace extends ObservedObject {

    private String ipAddress;

    @Column(name = "ipAddress", nullable = false, insertable = true, updatable = true, length = 40, precision = 0)
    @Basic
    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    private String path;

    @Column(name = "path", nullable = false, insertable = true, updatable = true, length = 65535, precision = 0)
    @Basic
    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    private List<Project> projects;

    @ManyToMany(fetch = LAZY, cascade = ALL)
    @OrderBy("name asc")
    @JoinTable(name = "workspace_has_project",
               joinColumns = { @JoinColumn(name = "workspace_workspaceId")},
               inverseJoinColumns={@JoinColumn(name="project_projectId")})
    public List<Project> getProjects() {
        return projects;
    }

    public void setProjects(List<Project> projects) {
        this.projects = projects;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Workspace)) return false;
        if (!super.equals(o)) return false;

        Workspace workspace = (Workspace) o;

        if (!ipAddress.equals(workspace.ipAddress)) return false;
        if (!path.equals(workspace.path)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + ipAddress.hashCode();
        result = 31 * result + path.hashCode();
        return result;
    }

    @Transient
    public String getUUID() {
        return generateUUID("" + getObservedEntityId(), getOwner().getUsername(), getIpAddress(), getPath(), getDataTimeWithoutNanos(getCreationDate()));
    }
}
